package com.example.sxt_practise.reflection;



import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * jdk1.6引入了动态编译机制
 *  应用场景: 1.可以做一个浏览器端编写java代码,上传服务器端编译和运行的在线测评系统
 *           2. 服务器动态加载某些类文件进行编译
 *     实现: 1. 通过Runtime调用javac,启用新的进程去操作
 *           2. 通过JavaCompiler动态编译
 * @author gaofeng
 * @date 2022年06月05日 17:47
 */
public class DynamicCompileTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException, InvocationTargetException, NoSuchMethodException, IllegalAccessException {
//            dynamicCompile("D:/project/project_code/XT-PRACTISE/src/反射/Test.java") ;

            // 通过io流将字符串转储成一个临时文件,然后在调用动态编译方法
            String str = "代码" ;
//        dynamicCompileByRuntime() ;
        dynamicCompileByReflect();

    }

    public static Boolean dynamicCompile(String sourceFile) {
        JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
        int result = compiler.run(null, null, null, sourceFile);
        return result == 0 ;
    }

    public static void dynamicCompileByRuntime() throws IOException {
        Runtime runtime = Runtime.getRuntime();
        Process result = runtime.exec("java -cp D:/project/project_code/SXT-PRACTISE/src/反射 Test");
        InputStream inputStream = result.getInputStream();
        byte[] flush = new byte[1024] ;
        while (inputStream.read(flush) != -1) {
            System.out.println(inputStream.read(flush));
        }
    }

    public static void dynamicCompileByReflect() throws IOException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        URL[] urls = new URL[] {new URL("file:/" + "D:/project/project_code/SXT-PRACTISE/src/反射")} ;
        URLClassLoader urlClassLoader = new URLClassLoader(urls);
        Class<?> test = urlClassLoader.loadClass("Test");

        Method main = test.getMethod("main", String[].class);
        // 由于可变参数jdk1.5之后才有, 编译成 main.invoke(null, "aa", "bb"); ,就会参数个数不匹配,要转成Object
        Object invoke = main.invoke(null, (Object) new String[]{"aa", "bb"});
        System.out.println(invoke);
    }
}
